﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class createRoomScript : MonoBehaviour {
	
	public GameObject roomsPanelPref;
	public string selectedMap;
	NetworkScript network;
	public UILabel myLabel;
	DataScript data;
	public chatSystem chatWindow;
	public UISlider mySlider;
	
	string initialMap;
	// Use this for initialization
	void Start () {
		string path = Application.dataPath + "/Maps";
		string[] mapArray = new string[1];
		
		if(Directory.Exists(path))
		{
			string[] maps = Directory.GetFiles(path, "*.xml"); 
			mapArray = new string[maps.Length];
			//Get all available maps for the player
			for(int i = 0; i < maps.Length; i++)
			{
				mapArray[i] = Path.GetFileName(maps[i]);
				//mapList.Add(mapArray[i]);
			}
		}
		//UISlider tmpSlide;
		//tmpSlide.startingForegroundPosition = tmpSlide.foregroundWidget.transform.position;
		int posCount = 0;

		for(int i = 0; i < mapArray.Length;i++)
		{
			string[] dataInfo = mapArray[i].Split('_');
			if(dataInfo[0] == "hid")
				continue;
			if(selectedMap == "")
				selectedMap = mapArray[i];

			mapArray[i] = mapArray[i].Substring(0,mapArray[i].Length - 4);
			createRoomPanel tmpBut = (GameObject.Instantiate(roomsPanelPref) as GameObject).GetComponent<createRoomPanel>();
			if(posCount == 0)
				tmpBut.setAsStart();

			tmpBut.parent = this;
			tmpBut.setMapName(mapArray[i]);
			tmpBut.transform.parent = this.transform;
			Vector3 tmpPos = new Vector3(-10, 130 - posCount * 100,2);
			posCount ++;
			tmpBut.transform.localPosition = tmpPos;
			tmpBut.transform.localScale = new Vector3(1,1,1);
			//roomPanelBut.Add(tmpBut);
		}
		//selectedMap = mapArray[0];
		initialMap = selectedMap;
		network = GameObject.FindGameObjectWithTag("NetworkManager").GetComponent<NetworkScript>();
		data = GameObject.FindGameObjectWithTag("DataManager").GetComponent<DataScript>();
	}
	
	public void createTheRoom()
	{
		string com = myLabel.text;
		for(int i = 0; i < com.Length; i++)
		{
			if(com[i] == '_')
				com = StringTools.ReplaceAt(com,i,' ');
		}
		string playerName = data.playerName;
		int AvatarID = DataScript.GetCurrentCharacter() + 1;
		//Debug.Log(AvatarID);
		
		Debug.Log(selectedMap);
		data.loadedLevel = selectedMap;
		data.isServer = true;
		chatWindow.enabled = true;
		
		string appendedCom = " ";
		appendedCom = appendedCom.Insert(appendedCom.Length - 1,com);
		appendedCom = appendedCom.Insert(appendedCom.Length - 1,"_" + playerName);
		appendedCom = appendedCom.Insert(appendedCom.Length - 1,"_" + selectedMap);
		appendedCom = appendedCom.Insert(appendedCom.Length - 1,"_" + AvatarID.ToString());
		
		network.startServer(appendedCom);
	}
	bool oneShot = true;
	// Update is called once per frame
	void Update () {
		if(oneShot)
		{
			oneShot = false;
			selectedMap = initialMap;
		}
		
	}
}
